package br.com.sgdc.view.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;

public class SplitFile {
	private File file;
	
	private LineNumberReader linha;
	
	private int qtdTotalLinha;
	private int qtdLinhaArqUm;
	private int qtdLinhaArqDois;

	private BufferedReader br;

	public SplitFile(File file) {
		try {
			this.file = file;
			
			linha = new LineNumberReader(new FileReader(file));
			linha.skip(file.length());
			
			qtdTotalLinha = linha.getLineNumber()+1; 
			qtdLinhaArqUm = 0;
			qtdLinhaArqDois = 0;
			
			if((qtdTotalLinha % 2) == 0){
				qtdLinhaArqUm = qtdTotalLinha / 2;
				qtdLinhaArqDois = qtdLinhaArqUm;
			} else {
				qtdLinhaArqUm = (qtdTotalLinha / 2) + 1;
				qtdLinhaArqDois = qtdLinhaArqUm - 1;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void split() throws IOException {
		br = new BufferedReader(new FileReader(file));
		
		File fileOne = new File(file.getParent()+"\\arquivo_1.txt");
		BufferedWriter bw1 = new BufferedWriter(new FileWriter(fileOne,false));
		for (int i = 0; i < qtdLinhaArqUm; i++) {
			if(br.ready()){
				String linha = br.readLine();
				if (linha != null && linha.length() > 0) {
					bw1.write(linha+System.lineSeparator());
				}
			}
		}
		
		
		File fileTwo = new File(file.getParent()+"\\arquivo_2.txt");
		BufferedWriter bw2 = new BufferedWriter(new FileWriter(fileTwo,false));
		for (int i = 0; i < qtdLinhaArqDois; i++) {
			if(br.ready()){
				String linha = br.readLine();
				if (linha != null && linha.length() > 0) {
					bw2.write(linha+System.lineSeparator());
				}
			}
		}
		bw1.flush();
		bw1.close();
		
		bw2.flush();
		bw2.close();
	}

	public static void main(String[] args) {
		try {
			SplitFile file = new SplitFile(new File("C:\\Users\\Leandro\\Documents\\leandro.txt"));
			file.split();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
